package bootstrap

import (
	"lib/app"
	"lib/bootstrap/http_api"
	"lib/bootstrap/jsonrpc_api"
	"lib/logger"
	"os"
	"os/signal"
)

func Bootstrap(callback func(shutdownQueue *chan bool)) {
	initLogger()
	perAction()
	shutdownQueue := make(chan bool)
	go shutdown(&shutdownQueue)
	go callback(&shutdownQueue)
	handleSignals(&shutdownQueue)
	initWebApi()
	initJsonRpcMethod()
	httpApiServerStartup()
}

func initLogger() {
	logger.Factory()
}

func perAction() {
	// do something before the startup.
}

func shutdown(signal *chan bool) {
	logger.Debug("Started waiting for shutdown.")
	_ = <-*signal
	logger.Debug("Got shutdown signal")
	shutdownErr := app.Shutdown()
	if shutdownErr != nil {
		logger.Errorf("Failed to stop backend service. Err is %v.", shutdownErr)
	}
}

func handleSignals(shutdownQueue *chan bool) {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	go func() {
		for sig := range c {
			if sig == os.Interrupt {
				*shutdownQueue <- true
			}
		}
	}()
}

func httpApiServerStartup() {
	startupErr := app.Startup("0.0.0.0:3200")
	if startupErr != nil {
		logger.Errorf("Failed to start backend service. Err is %v.", startupErr)
	}
}

func initWebApi() {
	http_api.HttpApiBootstrap()
}

func initJsonRpcMethod() {
	jsonrpc_api.JsonRpcMethodBootstrap()
}
